<!-- examMgr -->
<script lang="ts" setup>
import { Page } from '@vben/common-ui';
import { reactive, ref, onMounted, watch } from "vue"
import { useRouter } from 'vue-router'
import { ElMessageBox } from "element-plus"
import { $t } from '@vben/locales';
import { getExamInfoWithSituationApi, getCourseInfoApi, copyExamInfoApi, deleteExamInfoApi } from "#/api/manage/examination-mgr"
import { getOrgTreeApi, getGroupOrgCertTreeApi } from '#/api/system/orgMgr';
import { trimStringParams } from '#/utils/trimStringParams'

import { Query, ExamList, EditExamDialog, ChoseModeDialog } from "./modules/examination-mgr"
import { useTabs } from '@vben/hooks';
const { setTabTitle } = useTabs();

const router = useRouter()
const queryRef = ref<InstanceType<typeof Query> | null>(null)
const editExamDialogRef = ref<InstanceType<typeof EditExamDialog> | null>(null)
const choseModeDialogRef = ref<InstanceType<typeof ChoseModeDialog> | null>(null)
const defaultQueryData = {
  courseId: '',
  mode: '',
  organizationId: null,
  name: ''
}
const queryData = reactive({ ...defaultQueryData })
const tableData = ref<any>([])
const courseList = ref<any>([])
const orgTree = ref<any>([])
const loadingFlag = reactive([0, 0, 0])
const loading = ref(false)
const pageData = reactive<any>({
  total: 0,
  curPage: 1,
  pageSize: 10
})

const getCourseList = () => {
  const params = {};
  loadingFlag[0] = 1;
  getCourseInfoApi(params).then((res) => {
    let { data = [] } = res;
    courseList.value = data;
  }).finally(() => {
    loadingFlag[0] = 0;
  })
}

// 递归处理树型数据
const processTreeData = (data: any[]): any[] => {
  if (!Array.isArray(data)) return []
  
  return data.map(item => {
    const processedItem = {
      ...item,
      value: item.id,
      label: item.name,
      orgId: item.id,
      orgName: item.name,
      children: item.children ? processTreeData(item.children) : []
    }
    
    // 如果当前节点有子节点，递归处理
    if (processedItem.children && processedItem.children.length > 0) {
      processedItem.children = processTreeData(processedItem.children)
    }
    
    return processedItem
  })
}


const getOrgTree = () => {
  const params = {
    status: 'enable',
    curPage: 1
  };
  loadingFlag[2] = 1;
  getGroupOrgCertTreeApi(params).then((res) => {
    let { data = [] } = res;
    orgTree.value = processTreeData(data);
  }).finally(() => {
    loadingFlag[2] = 0;
  })
}
const reset = () => {
  Object.assign(queryData, defaultQueryData)
  onQuery()
}
const onQuery = () => {
  const params = {
    curPage: pageData.curPage,
    pageSize: pageData.pageSize
  } as any;
  const trimData = trimStringParams(queryData)
  console.log(trimData)
  Object.keys(trimData).forEach(key => {
    const kVal = trimData[key as keyof typeof trimData]
    if (kVal) {
      params[key] = kVal
    }
  })
  loadingFlag[1] = 1;
  console.log(params)
  getExamInfoWithSituationApi(params).then((res) => {
    let { pageInfo, data = [] } = res
    pageData.total = pageInfo.totalRows
    tableData.value = data
  }).finally(() => {
    loadingFlag[1] = 0;
  })
}
const onSizeChange = (size: Number) => {
  pageData.pageSize = size
  pageData.curPage = 1
  onQuery()
}
const onCurrentChange = (curPage: Number) => {
  pageData.curPage = curPage
  onQuery()
}
const onAddExam = () => {
  choseModeDialogRef.value?.inint()
}

const choseExamType = (type: string) => {
  switch (type) {
    case 'ONLINE': {
      editExamDialogRef.value?.inint('online', null)
      break;
    }
    case 'OFFLINE': {
      editExamDialogRef.value?.inint('offline', null)
      break;
    }
    default: { }
  }
}

const copyExam = (data: any) => {
  console.log(data)
  ElMessageBox.confirm(
    $t('common.submitTxt', [$t('exam.copyExamTxt')]),
    $t('common.tipTxt'),
    {
      confirmButtonText: $t('common.submitTxt'),
      cancelButtonText: $t('common.cancelTxt'),
      type: 'warning',
    }
  )
    .then(() => {
      loadingFlag[1] = 1;
      copyExamInfoApi(data.id).then((res) => {
        console.log(res)
        onQuery()
      }).finally(() => {
        loadingFlag[1] = 0;
      })
    })
    .catch(() => { })
}

const deleteExam = (data: any) => {
  console.log(data)
  ElMessageBox.confirm(
    $t('common.submitTxt', [$t('exam.deleteExamTxt')]),
    $t('common.tipTxt'),
    {
      confirmButtonText: $t('common.submitTxt'),
      cancelButtonText: $t('common.cancelTxt'),
      type: 'warning',
    }
  )
    .then(() => {
      loadingFlag[1] = 1;
      deleteExamInfoApi(data.id).then((res: any) => {
        console.log(res)
        onQuery()
      }).finally(() => {
        loadingFlag[1] = 0;
      })
    })
    .catch(() => { })
}

const editExam = (data: any) => {
  editExamDialogRef.value?.inint(data.mode, data)
}

const detailExam = (data: any) => {
  if (data.organizationIdList.length === 0) {
    ElMessageBox.confirm(
      $t('exam.releaseOrgTxt'),
      $t('common.tipTxt'),
      {
        confirmButtonText: $t('common.submitTxt'),
        cancelButtonText: $t('common.cancelTxt'),
        type: 'warning',
        showCancelButton: false
      },
    )
      .then(() => {
        console.log(12)
      })
      .catch(() => { })
  } else {
    router.push({
      query: {
        id: data.id
      },
      name: 'ExaminationDetail'
    }).then(() => {
      setTabTitle(`${data.name}${$t('common.detailTxt')}`)
    });
  }
}

const toCorrect = (exam: any, org: any) => {
  router.push({
    query: {
      id: exam.id,
      orgId: org?.id
    },
    name: 'ExaminationCorrection'
  }).then(() => {
    setTabTitle(exam.name)
  });
}

watch(
  () => loadingFlag,
  (val) => {
    if (val) {
      const isLoading = val.some(i => i === 1)
      loading.value = isLoading
    }
  },
  { deep: true },
)

onMounted(() => {
  getCourseList()
  getOrgTree()
  onQuery()
})
</script>
<template>
  <Page class="h-full">
    <div class="flex flex-col h-full bg-[#fff] p-[24px] rounded-sm">
      <Query :courseList="courseList" :orgTree="orgTree" v-model="queryData" @queryData="onQuery" @reset="reset"
        ref="queryRef">
      </Query>
      <div class="mb-[16px]">
        <el-button type="primary" @click="onAddExam">{{ $t('exam.addExamBtn') }}</el-button>
      </div>
      <div v-loading="loading" class="min-h-[1px] flex-1 overflow-auto">
        <ExamList :tableList="tableData" :copyExam="copyExam" :editExam="editExam" :detailExam="detailExam"
          :deleteExam="deleteExam" :toCorrect="toCorrect"></ExamList>
      </div>
      <ElPagination class="pagination pt-[15px]" size="small" layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.total" :page-sizes="[10, 20, 50, 100]" @size-change="onSizeChange"
        @current-change="onCurrentChange">
      </ElPagination>
    </div>
    <EditExamDialog ref="editExamDialogRef" :processTreeData="processTreeData" :courseList="courseList" @updateList="onQuery">
    </EditExamDialog>
    <ChoseModeDialog ref="choseModeDialogRef" @choseExamType="choseExamType"></ChoseModeDialog>
  </Page>
</template>
